import os
import glob
import pandas as pd
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
import logging
import json

app = Flask(__name__)
CORS(app)  # 解决跨域问题
cache = {}  # 全局缓存
app.json.ensure_ascii = False

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(message)s')
# 加载文档1（试卷映射）
def load_doc1():
    doc1_path = os.path.join('gzkf', 'zhuguanti', '*.xlsx')
    files = glob.glob(doc1_path)
    if not files:
        return {}
    df = pd.read_excel(files[0])
    return dict(zip(df['试卷号'], df['考试课程']))


# 解析文档2（按日期）
def parse_doc2(date_str):
    # 检查缓存
    if date_str in cache:
        return cache[date_str]

    # 读取Excel文件
    file_path = os.path.join('gzkf', 'dangtian', 'zhuguanti', f"{date_str}.xlsx")
    if not os.path.exists(file_path):
        return []

    df = pd.read_excel(file_path)
    paper_map = load_doc1()

    # 试卷号统计
    paper_counts = df['试卷号'].value_counts().reset_index()
    paper_counts.columns = ['试卷号', '数量']
    paper_counts['考试课程'] = paper_counts['试卷号'].map(paper_map)
    paper_counts['日期'] = date_str

    # 格式转换
    # result = [{
    #     '序号': idx + 1,
    #     '日期': row['日期'],
    #     '试卷号': row['试卷号'],
    #     '考试课程': row.get('考试课程'),
    #     '数量': int(row['数量'])
    # } for idx, row in paper_counts.iterrows()]
    paper_counts_sorted = paper_counts.sort_values(by='试卷号', ascending=True)
    paper_counts_sorted = paper_counts_sorted.reset_index(drop=True)

    result = []
    for idx, row in paper_counts_sorted.iterrows():
        # 检查所有字段是否含NaN
        if not any(pd.isna(val) for val in row.values):
            result.append({
                '序号': idx + 1,
                '日期': row['日期'],
                '试卷号': row['试卷号'],
                '考试课程': row.get('考试课程', '未知试卷'),
                '数量': int(row['数量'])
            })

    # 缓存非当天数据
    today = datetime.now().strftime("%Y%m%d")
    if date_str != today:
        cache[date_str] = result

    return result

@app.route('/')  # ← Handles requests to "/"
def home():
    return render_template('index.html')  # Or render_template('index.html')

# 获取日期范围
@app.route('/api/dates', methods=['GET'])
def get_dates():
    dates = []
    start_date = datetime(2025, 6, 6)
    for i in range(29):  # 6.6-7.4共29天
        date_str = (start_date + timedelta(days=i)).strftime("%Y%m%d")
        dates.append(date_str)
    return jsonify(dates)


# 获取数据
@app.route('/api/data', methods=['GET'])
def get_data():
    date_str = request.args.get('date', '')
    data = parse_doc2(date_str)
    logging.debug(f"生成数据: {jsonify(data)}")
    print(jsonify(data))
    #response = jsonify(data)
    #response.headers["Content-Type"] = "application/json; charset=utf-8"

    return jsonify(data)


# 刷新缓存
@app.route('/api/refresh', methods=['POST'])
def refresh_cache():
    global cache
    cache = {}
    return jsonify({'status': '缓存已清空'})


if __name__ == '__main__':
    # 创建示例目录结构
    os.makedirs('gzkf/zhuguanti', exist_ok=True)
    os.makedirs('gzkf/dangtian/zhuguanti', exist_ok=True)
    app.run(debug=True, port=5000)